package com.yhx.testDemo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;

import java.util.List;

/**
 * fastjson工具类
 */
public class FastJsonUtils {

    private static final SerializeConfig config;

    private static final String dateFormat="yyyy-MM-dd HH:mm:ss";

    static {
        config = new SerializeConfig();
        config.put(java.util.Date.class, new SimpleDateFormatSerializer(dateFormat)); // 使用yyyy-MM-dd HH:mm:ss
        config.put(java.sql.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
    }

    private static final SerializerFeature[] features = {SerializerFeature.WriteMapNullValue, // 输出空置字段
            SerializerFeature.WriteNullListAsEmpty, // list字段如果为null，输出为[]，而不是null
            SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null，输出为0，而不是null
            SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null，输出为false，而不是null
            SerializerFeature.DisableCircularReferenceDetect,//禁止循环引用检测
            SerializerFeature.WriteNullStringAsEmpty // 字符类型字段如果为null，输出为""，而不是null

    };

    public static String toJSONStringWithDateFormat(Object object,String dateFormatStr){
        return JSON.toJSONStringWithDateFormat(object, dateFormatStr, features);
    }

    public static String toJSONString(Object object) {

        return JSON.toJSONString(object, config, features);
    }

    public static String toJSONNoFeatures(Object object) {
        if(object == null){
            return null;
        }
        return JSON.toJSONString(object, config);
    }



    public static Object toBean(String text) {
        return JSON.parse(text);
    }

    public static <T> T toBean(String text, Class<T> clazz) {
        return JSON.parseObject(text, clazz);
    }

    // 转换为数组
    public static <T> Object[] toArray(String text) {
        return toArray(text, null);
    }

    // 转换为数组
    public static <T> Object[] toArray(String text, Class<T> clazz) {
        return JSON.parseArray(text, clazz).toArray();
    }

    // 转换为List
    public static <T> List<T> toList(String text, Class<T> clazz) {
        return JSON.parseArray(text, clazz);
    }

    public static JSONObject toJSONObject(String text){
        return JSON.parseObject(text);
    }

}
